package com.lawliet.example.service.system.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lawliet.example.model.system.SysPermission;
import com.lawliet.example.model.system.SysRolePermission;
import com.lawliet.example.model.system.vo.PermissionTreeVO;
import com.lawliet.example.repository.system.SysPermissionMapper;
import com.lawliet.example.repository.system.SysRolePermissionMapper;
import com.lawliet.example.service.system.SysPermissionService;
import com.lawliet.example.service.system.SysRolePermissionService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission> implements SysPermissionService {

    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;

    /**
     * 删除权限
     * @param ids 权限集合
     */
    @Override
    @Transactional
    public void deleteBach(String ids) {
        List<String> parentPermissionList = Arrays.asList(ids.split(","));
        for(String permissionId:parentPermissionList){
            List<SysPermission> all = this.list();
            //待删除的权限id以及子权限id集合
            List<Long> deletePer = new ArrayList<>();
            collectChildIds(all, Long.parseLong(permissionId), deletePer);
            deletePer.add(Long.parseLong(permissionId));
            // 删除权限
            this.removeByIds(deletePer);
            // 删除角色-权限绑定关系
            for(Long deleteId:deletePer){
                LambdaQueryWrapper<SysRolePermission> con = new LambdaQueryWrapper<>();
                con.eq(SysRolePermission::getPermissionId,deleteId);
                sysRolePermissionMapper.delete(con);
            }
        }
    }

    @Override
    public List<PermissionTreeVO> getTree() {
        List<SysPermission> all = list();
        List<PermissionTreeVO> tree = buildTree(all, null); // 根节点 parentId 为 null
        return tree;
    }

    /**
     * 构建树
     * @param all 权限列表
     * @param parentId 父节点
     * @return
     */
    private List<PermissionTreeVO> buildTree(List<SysPermission> all, Long parentId) {
        return all.stream()
                .filter(p -> Objects.equals(p.getParentId(), parentId))
                .map(p -> {
                    PermissionTreeVO vo = new PermissionTreeVO();
                    try {
                        BeanUtils.copyProperties(p, vo);
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    } catch (InvocationTargetException e) {
                        throw new RuntimeException(e);
                    }
                    vo.setChildren(buildTree(all, p.getId()));
                    return vo;
                })
                .sorted(Comparator.comparing(PermissionTreeVO::getSort, Comparator.nullsLast(Integer::compareTo)))
                .collect(Collectors.toList());
    }

    /**
     * 递归找到当前权限的子权限
     * @param all 所有的权限
     * @param parentId 父id
     * @param result 待删除权限id集合
     */
    private void collectChildIds(List<SysPermission> all, Long parentId, List<Long> result) {
        for (SysPermission p : all) {
            if (Objects.equals(p.getParentId(), parentId)) {
                result.add(p.getId());
                collectChildIds(all, p.getId(), result);
            }
        }
    }
}
